﻿using DataLibrary;
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;
namespace Common
{
    public class PublicMethod
    {
        //private TicketSystemEntities tse = new TicketSystemEntities();
        //加密
        //构造一个对称算法
        private SymmetricAlgorithm mCSP = new TripleDESCryptoServiceProvider();
        private string sKey = "qJzGEh6hESZDVJeCnFPGuxzaiB7NLQM5";
        private string sIV = "andyliu1234=";
        #region 加密解密函数
        /// <summary>
        /// 字符串的加密
        /// </summary>
        /// <param name="Value">要加密的字符串</param>
        /// <param name="sKey">密钥，必须32位</param>
        /// <param name="sIV">向量，必须是12个字符</param>
        /// <returns>加密后的字符串</returns>
        public string EncryptString(string Value)
        {
            try
            {
                ICryptoTransform ct;
                MemoryStream ms;
                CryptoStream cs;
                byte[] byt;
                mCSP.Key = Convert.FromBase64String(sKey);
                mCSP.IV = Convert.FromBase64String(sIV);
                //指定加密的运算模式
                mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
                //获取或设置加密算法的填充模式
                mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV);//创建加密对象
                byt = Encoding.UTF8.GetBytes(Value);
                ms = new MemoryStream();
                cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
                cs.Write(byt, 0, byt.Length);
                cs.FlushFinalBlock();
                cs.Close();
                return Convert.ToBase64String(ms.ToArray());
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "出现异常", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return ("Error in Encrypting " + ex.Message);
            }
        }
        /// <summary>
        /// 解密字符串
        /// </summary>
        /// <param name="Value">加密后的字符串</param>
        /// <param name="sKey">密钥，必须32位</param>
        /// <param name="sIV">向量，必须是12个字符</param>
        /// <returns>解密后的字符串</returns>
        public string DecryptString(string Value)
        {
            try
            {
                ICryptoTransform ct;//加密转换运算
                MemoryStream ms;//内存流
                CryptoStream cs;//数据流连接到数据加密转换的流
                byte[] byt;
                //将3DES的密钥转换成byte
                mCSP.Key = Convert.FromBase64String(sKey);
                //将3DES的向量转换成byte
                mCSP.IV = Convert.FromBase64String(sIV);
                mCSP.Mode = System.Security.Cryptography.CipherMode.ECB;
                mCSP.Padding = System.Security.Cryptography.PaddingMode.PKCS7;
                ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV);//创建对称解密对象
                byt = Convert.FromBase64String(Value);
                ms = new MemoryStream();
                cs = new CryptoStream(ms, ct, CryptoStreamMode.Write);
                cs.Write(byt, 0, byt.Length);
                cs.FlushFinalBlock();
                cs.Close();
                return Encoding.UTF8.GetString(ms.ToArray());
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message, "出现异常", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return ("Error in Decrypting " + ex.Message);
            }
        }
        #endregion
        /// <summary>
        /// 导出数据
        /// </summary>
        /// <param name="dataGridView1"></param>

        public void export(DataGridView dataGridView1)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Excel files (*.xls)|*.xls";
            saveFileDialog.FilterIndex = 0;
            saveFileDialog.RestoreDirectory = true;
            saveFileDialog.CreatePrompt = true;
            saveFileDialog.Title = "导出Excel文件到";
            saveFileDialog.ShowDialog();
            try
            {
                Stream myStream;
                myStream = saveFileDialog.OpenFile();
                StreamWriter sw = new StreamWriter(myStream, System.Text.Encoding.GetEncoding("gb2312"));
                string str = "";
                //写标题  
                for (int i = 0; i < dataGridView1.ColumnCount; i++)
                {
                    if (i > 0)
                    {
                        str += "\t";
                    }
                    str += dataGridView1.Columns[i].HeaderText;
                }

                sw.WriteLine(str);
                //写内容 
                int a = dataGridView1.Rows.Count;

                for (int j = 0; j < a; j++)
                {
                    string tempStr = "";
                    for (int k = 0; k < dataGridView1.Columns.Count; k++)
                    {
                        if (k > 0)
                        {
                            tempStr += "\t";
                        }
                        //判断字符串是不是数字字符串
                        bool IsNumber = false;
                        var count=dataGridView1.Rows[j].Cells[k].Value.ToString();
                        for (var i = 0; i < count.Length; i++)
                        {
                            System.Text.RegularExpressions.Regex rex = new System.Text.RegularExpressions.Regex(@"^\d+$");
                            if (rex.IsMatch(count[i].ToString()))
                            {
                                IsNumber = true;
                            }
                            else
                                IsNumber = false;
                        }
                        //效率太低，wt已修改为上述方法。
                        //try
                        //{
                        //    for (var i = 0; i < count.Length; i++)
                        //    {
                        //        var result = int.Parse(count[i].ToString());

                        //    }
                        //    IsNumber = true;
                        //}
                        //catch
                        //{
                        //    IsNumber = false;
                        //}
                        if (IsNumber)
                        {
                            //手机号导出格式
                            if (count.Length == 11)
                            {
                                tempStr +=count.Substring(0, 3) + "-" + count.Substring(3, 4) + "-" + count.Substring(7, 4);
                            }
                            //身份证号导出格式
                            else if (count.Length == 18)
                            {
                                tempStr += count.Substring(0, 6) + " " + count.Substring(6, 4) + " " + count.Substring(10, 4) + " " + count.Substring(14, 4);
                            }
                            //税号导出格式
                            else if (count.Length == 15)
                            {
                                tempStr += count.Substring(0, 5) + " " + count.Substring(5, 5) + " " + count.Substring(10, 5);
                            }
                            //导游卡号或传真导出格式
                            else if (count.Length < 11)
                            {
                                tempStr += count;
                            }
                            //银行卡导出格式
                            else
                            {
                                tempStr += count.Substring(0, 4) + " " + count.Substring(4, 4) +" "+ count.Substring(8, count.Length - 8);
                            }
                        }
                        else 
                        {
                            tempStr +=dataGridView1.Rows[j].Cells[k].Value.ToString();
                        }
                    }
                    sw.WriteLine(tempStr);
                }
                MessageBox.Show("导出成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                sw.Close();
                myStream.Close();
            }
            catch (Exception)
            {
                MessageBox.Show("导出错误");
            }
        }
        /// <summary>
        /// 验证操作员权限_导出
        /// </summary>
        public void CanExport(Button txt_Export, List<string> Rights)
        {
            txt_Export.Enabled = false;
            for (var i = 0; i < Rights.Count; i++)
            {
                if (Rights[i] == "可以导出数据")
                {
                    txt_Export.Enabled = true;
                }
            }
        }
        /// <summary>
        /// 验证操作员权限_打印
        /// </summary>
        /// 
        public void CanPrint(Button txt_Print, List<string> Rights)
        {
            txt_Print.Enabled = false;
            for (var i = 0; i < Rights.Count; i++)
            {
                if (Rights[i] == "可以打印数据")
                {
                    txt_Print.Enabled = true;
                }
            }
        }
        /// <summary>
        /// 验证操作员权限_编辑操作员
        /// </summary>
        public void CanMotifyOperator(Button txt_Add, Button txt_Update, Button txt_Delete, List<string> Rights, string name)
        {
            txt_Add.Enabled = false;
            txt_Update.Enabled = false;
            txt_Delete.Enabled = false;
            for (var i = 0; i < Rights.Count; i++)
            {
                if (Rights[i] == "最高权限")
                {
                    txt_Add.Enabled = true;
                    txt_Delete.Enabled = true;
                    txt_Update.Enabled = true;
                }
            }
        }
        public void CanMotifyOperator(Button txt_Add, Button txt_Update, List<string> Rights, string name)
        {
            txt_Add.Enabled = false;
            txt_Update.Enabled = false;
            for (var i = 0; i < Rights.Count; i++)
            {
                if (Rights[i] == "最高权限")
                {
                    txt_Add.Enabled = true;
                    txt_Update.Enabled = true;
                }
            }
        }
        /// <summary>
        /// 验证操作员权限_显示电话
        /// </summary>
        /// <param name="Rights"></param>
        /// <returns></returns>
        public bool DisplayPhone(List<string> Rights)
        {
            int a = 0;
            for (var i = 0; i < Rights.Count; i++)
            {
                if (Rights[i] == "显示电话")
                {
                    a = 1;
                }
            }
            if (a == 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
        /// <summary>
        /// 验证电话号码
        /// </summary>
        /// <param name="str_telephone"></param>
        /// <returns></returns>
        public bool IsTelephone(string str_telephone)
        {
            try
            {
                for (var i = 0; i < str_telephone.Length; i++)
                {
                    var result = int.Parse(str_telephone[i].ToString());//这里如果转换不成功会抛错

                }
                if (str_telephone.Length == 11)
                {
                    return true;
                }
                else if (str_telephone.Length == 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {             
                return false;
            }
        }
        /// <summary>
        /// 验证银行卡号
        /// </summary>
        /// <param name="str_AccountNumber"></param>
        /// <returns></returns>
        public bool IsAccountNumber(string str_AccountNumber)
        {
            try
            {
                for (var i = 0; i < str_AccountNumber.Length; i++)
                {
                    var result = int.Parse(str_AccountNumber[i].ToString());//这里如果转换不成功会抛错
                    
                }
                if (str_AccountNumber.Length == 0)
                {
                    return true;
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 验证身份号
        /// </summary>
        /// <param name="str_IDNumber"></param>
        /// <returns></returns>
        public bool IsIDNumber(string str_IDNumber)
        {
            try
            {
                if (str_IDNumber.Length == 18)
                {
                    return true;
                }
                else if (str_IDNumber.Length==0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch
            {
                return false;
            }
        }

        public static string RemoveLastChar(string str, string value)
        {
            int _finded = str.LastIndexOf(value);
            if (_finded != -1)
            {
                return str.Substring(0, _finded);
            }
            return str;
        }
    }
}
